package com.tencent.qf.systembiz.service;

import com.alibaba.fastjson.JSON;
import com.tencent.qf.common.log.ErrorLog;
import com.tencent.qf.mybatis.pojo.PageRequest;
import com.tencent.qf.mybatis.pojo.PageResult;
import com.tencent.qf.system.api.ErrorLogApi;
import com.tencent.qf.system.api.log.ErrorLogDTO;
import com.tencent.qf.systembiz.convert.SystemConvert;
import com.tencent.qf.systembiz.dal.ErrorLogDO;
import com.tencent.qf.systembiz.dal.ApiErrorLogExample;
import com.tencent.qf.systembiz.dao.ErrorLogDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;

/**
 * Copyright (C) 2022 Limited, a Tencent company. All rights reserved.
 *
 * @author p_htaozhou@tencent.com
 * @create: 2022/9/8 15:14
 */
@Service
@Slf4j
public class ErrorLogService implements ErrorLogApi {

    @Resource
    private ErrorLogDao errorLogDao;

    @Override
    public Boolean createApiErrorLog(ErrorLogDTO errorLog) {
        ErrorLogDO apiErrorLogDO = SystemConvert.INSTANCE.apiErrorLogDTO2DO(errorLog);
        return errorLogDao.insertSelective(apiErrorLogDO) > 0;
    }

    public PageResult<ErrorLog> getAllErrorLog(PageRequest<ErrorLog> request) {
        ApiErrorLogExample example = new ApiErrorLogExample();
        example.setOrderByClause(" create_time ");
        long count = errorLogDao.countByExample(example);

        PageResult<ErrorLog> pageResult = new PageResult<>();
        pageResult.setTotal(count);
        pageResult.setPage(request.getPageNo());
        pageResult.setPageSize(request.getPageSize());
        Integer pageSize = request.getPageSize();
        List<ErrorLogDO> apiErrorLogDOList = errorLogDao.selectByPage((request.getPageNo() - 1) * pageSize, pageSize);
        log.info("ErrorLogService.getAllErrorLog errorLogDao response: {}", JSON.toJSONString(apiErrorLogDOList));
        List<ErrorLog> apiErrorLogList = apiErrorLogDOList.stream().map(SystemConvert.INSTANCE::apiErrorLogDO2VO).collect(Collectors.toList());
        pageResult.setList(apiErrorLogList);

        return pageResult;
    }
}
